package com.ruoyi.web.TCPtest;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

@Service
public class TcpClientService {

    public String sendMessage(String host, int port, String message) {
        try (Socket socket = new Socket(host, port);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

            // 发送消息
            out.println(message);

            // 接收响应
            return in.readLine();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
